import csv

from io import StringIO
import logging
import time
from ..models import HostMachineInfo, HostMachineResourceInfoDict
from ..baseapp import db, tasks_manager, app
from ..utils.tasks_manager import Task
from ..utils.docker_operator_client import DockerOperatorClient

logger = logging.getLogger(__name__)
host_machine_info_status: dict[int, HostMachineResourceInfoDict] = {}


class PullHostMachineStatusTask(Task):
    """
    拉取主机状态的任务
    """

    def run(self):
        while True:
            with app.app_context():
                self._handler()

    def _handler(self):
        hostmachines = get_all_host_machine_info()

        for hostmachine in hostmachines:
            try:
                cli = DockerOperatorClient(hostmachine.address)
                resource_info = cli.get_host_machine_resource_info()
                host_machine_info_status[hostmachine.id] = resource_info
            except Exception as e:
                import traceback

                traceback.print_exc()
                print(e)
        time.sleep(1)


def create_host_machine_info(name, description, address):
    new_host = HostMachineInfo(name=name, description=description, address=address)
    db.session.add(new_host)
    db.session.commit()
    return new_host


def get_host_machine_info_by_id(host_id) -> HostMachineInfo:
    return HostMachineInfo.query.get(host_id)


def get_all_host_machine_info() -> list[HostMachineInfo]:
    return HostMachineInfo.query.all()


def update_host_machine_info(host_id, name=None, description=None, address=None):
    host = HostMachineInfo.query.get(host_id)
    if not host:
        return None
    if name:
        host.name = name
    if description:
        host.description = description
    if address:
        host.address = address
    db.session.commit()
    return host


def delete_host_machine_info(host_id):
    host = HostMachineInfo.query.get(host_id)
    if not host:
        return False
    db.session.delete(host)
    db.session.commit()
    return True


def export_host_machine_info_to_csv():
    hosts = HostMachineInfo.query.all()
    output = StringIO()
    writer = csv.writer(output)
    writer.writerow(["id", "name", "description", "address"])
    for host in hosts:
        writer.writerow([host.id, host.name, host.description, host.address])
    output.seek(0)
    return output.getvalue()


def import_host_machine_info_from_csv(csv_data):
    input = StringIO(csv_data)
    reader = csv.DictReader(input)
    for row in reader:
        new_host = HostMachineInfo(
            name=row["name"], description=row["description"], address=row["address"]
        )
        db.session.add(new_host)
    db.session.commit()
    return True


def ensure_default_host_exists():
    if not HostMachineInfo.query.first():
        default_host = HostMachineInfo(
            name="default",
            description="the machine that hosting the baco3 manager service",
            address="127.0.0.1:58080",
        )
        db.session.add(default_host)
        db.session.commit()


def get_host_machines_status_info():
    """
    Get the status of all host machines.
    """
    return host_machine_info_status


# 一个始终执行的任务，用来拉取各个宿主机的状态，存入dict中。
tasks_manager.submit(PullHostMachineStatusTask())
